package Controller

import (
	"computer_set/global"
	"github.com/gin-gonic/gin"
	"net/http"
)

// Controller/controller.go
func GetEfficacyWordCloud(c *gin.Context) {
	// 获取功效统计数据
	efficacyStats, err := getEfficacyStats()
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
			"error": "获取功效数据失败: " + err.Error(),
		})
		return
	}

	// 转换为词云需要的格式 [{"name": "功效名称", "value": 出现次数}]
	wordCloudData := make([]gin.H, 0)
	for _, stat := range efficacyStats {
		wordCloudData = append(wordCloudData, gin.H{
			"name":  stat.Efficacy,
			"value": stat.Count,
		})
	}

	c.JSON(http.StatusOK, wordCloudData)
}

// 功效统计结构体
type EfficacyStat struct {
	Efficacy string
	Count    int
}

// 获取功效统计数据
func getEfficacyStats() ([]EfficacyStat, error) {
	db := global.DB
	var stats []EfficacyStat

	// 使用GROUP BY直接统计数据库中的功效出现次数
	err := db.Raw(`
        SELECT efficacy AS efficacy, 
               COUNT(*) AS count 
        FROM bencaogangmu 
        WHERE efficacy != ''
        GROUP BY efficacy
        ORDER BY count DESC
    `).Scan(&stats).Error

	return stats, err
}
